const btns = document.querySelectorAll('button');

const LOCAL_KEY = '__theme__';

// 加载上次使用的主题名称
let curTheme = localStorage.getItem(LOCAL_KEY) || 'light'
// 设置上一次使用的主题
setTheme(curTheme);

// 系统主题
let autoTheme = false;
// 监听系统主题变化
const darkThemeQuery = window.matchMedia('(prefers-color-scheme: dark)');
const lightThemeQuery = window.matchMedia('(prefers-color-scheme: light)');

darkThemeQuery.addListener((e) => {
    //console.log('dark',e.matches)
    if(e.matches) {
        curTheme = 'dark';
        if(autoTheme) setTheme('dark');
    }
});
lightThemeQuery.addListener((e) => {
    //console.log('light',e.matches)
    if(e.matches) {
        curTheme = 'light';
        if(autoTheme) setTheme('light');
    }
});

/**
 * 切换主题
 *    修改自定义属性
 *    修改 localStorage
 * @param {string} theme 
 */
function setTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem(LOCAL_KEY, theme);
}

// 给按钮点击事件
btns.forEach((btn) => {
  btn.addEventListener('click', () => {

    // 按钮点击动作动画
    btn.classList.add('clicked');
    setTimeout(() => {
      btn.classList.remove('clicked');
    }, 200)

    // 判断不同按钮，点击执行不同动作
    const themeName = btn.dataset.theme;
    if(themeName === 'auto') {
        autoTheme = true;   // 自适应模式开启
        setTheme(curTheme); // 设置系统主题
    } else {
        setTheme(themeName);    // 设置选择的主题
    }
    
  });
})